package servlets;

import DAO.DbDao;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.ResultSet;

/**
 * Created by hadoop on 17-6-13.
 * 处理来自login.jsp的请求a
 */
@WebServlet(name = "LoginServlet",urlPatterns = {"/LoginServlet"})
public class LoginServlet extends HttpServlet{
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        String errMsg = "";
        //获取request请求参数
        String username = req.getParameter("username");
        String pass = req.getParameter("pass");
        //获取数据库信息
        ServletContext application = this.getServletContext();
//        String driver = application.getInitParameter("sqlDriver");
//        String url = application.getInitParameter("sqlUrl");
//        String user = application.getInitParameter("sqlUser");
//        String sqlPass = application.getInitParameter("sqlPass");
//        DbDao dao = new DbDao(driver,url,user,sqlPass);
        //使用GetConnListener提供的DbDao
        DbDao dao = (DbDao) application.getAttribute("DbDao");
        try {
            ResultSet rs = dao.query("select pass from user where username = ?", username);
            if(rs.next()){
                if(pass.equals(rs.getString("pass"))){
                    HttpSession session = req.getSession();
                    session.setAttribute("username",username);
                    req.getRequestDispatcher("/index.jsp").forward(req,resp);
                }else{
                    errMsg += "密码错误，请重新输入";
                }
            }else {
                errMsg += "用户不存在，请先注册";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(!errMsg.equals("")){
            req.setAttribute("errMsg", errMsg);
            req.getRequestDispatcher("/login").forward(req,resp);
        }

    }
}
